package com.shanghaionstar.remote.manager;

import android.content.Context;
import android.os.Message;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.onstar.cn.api.DealersService;
import com.onstar.cn.api.FootPrintService;
import com.onstar.cn.api.UsersService;
import com.onstar.cn.api.VehicleService;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.mvp.base.core.BaseService;
import com.onstar.cn.framework.network.HttpInjectUtils;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.mag.CoordinateEntity;
import com.onstar.cn.mag.dealer.AroundDealerRequestEntity;
import com.onstar.cn.mag.dealer.NavAroundDealerResponseEntity;
import com.onstar.cn.mag.dealer.ReqAroundDealersEntity;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.mag.poi.Coordinate;
import com.onstar.cn.mag.poi.FavoriteEntity;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.sqlite.entities.PollingEntity;
import com.onstar.cn.vehicle.entity.AdditionalDestinationInfo;
import com.onstar.cn.vehicle.entity.DestinationAddress;
import com.onstar.cn.vehicle.entity.DestinationLocation;
import com.onstar.cn.vehicle.entity.ErrorEnum;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.onstar.cn.vehicle.entity.VehicleCommand;
import com.onstar.cn.vehicle.entity.VehicleNAV;
import com.onstar.cn.vehicle.entity.VehicleTBT;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.DealerBrandType;
import com.shanghaionstar.nav.model.MapChoosePoiType;
import com.shanghaionstar.nav.model.MyFootprintDTO;
import com.shanghaionstar.nav.model.MyFootprintStatisticDTO;
import com.shanghaionstar.nav.model.NavInfoModel;
import com.shanghaionstar.nav.model.ResCode;
import com.shanghaionstar.service.VehicleManager;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.NetConnectUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.functions.Func0;

/**
 * Created by 6335yz on 2016/7/15.
 */
public class NavService extends BaseService {
    private LogManager log = LogManager.getInstance();
    private Context context;
    private VehicleManager manager;

    @Override
    public RequestEntity getRequestEntity() {
        return null;
    }

    @Override
    public Object jsonToBean(String json) {
        return null;
    }

    public NavService(Context context) {
        this.context = context;
        manager = new VehicleManager(context, Constants.CURRENT_SERVER_URL);
    }

    public Observable<String> doNavCommand(final NavInfoModel navInfoModel) {
//        ApplicationUtil.getInstance().isCommanding = true;
        return Observable.defer(new Func0<Observable<String>>() {
            @Override
            public Observable<String> call() {
                try {
                    return Observable.just(navCommand(navInfoModel));
                } catch (OnStarException e) {
                    ApplicationUtil.getInstance().isCommanding = false;
                    return Observable.error(e);
                }
            }
        });
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.POST)
    public String navCommand(final NavInfoModel navInfoModel) throws OnStarException {
        String requestId = null;
        RemoteCommandsType remoteCommandType = navInfoModel.remoteCommandsType;
        BusinessUtil.initPollingStatusBeforePolling(remoteCommandType, ApplicationUtil.getInstance().getVin(),manager);
        ApplicationUtil.getInstance().isCommanding = false;
        final Message msg = new Message();
        msg.getData().putString("source", "myself");// 记录msg来自MainTabActivity还是自己
        VehicleService service = new VehicleService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        String body;
        switch (remoteCommandType) {
            case COMMANDS_LOCATION:
                //no body
                body = "";
                requestEntity = service.commands(requestEntity, remoteCommandType, ApplicationUtil.getInstance().getVin(),body);
                break;
            case COMMANDS_TBT_ROUTE:
                body = tbt(navInfoModel.poiItemInfo);
                requestEntity = service.commands(requestEntity, remoteCommandType, ApplicationUtil.getInstance().getVin(),body);
                break;
            case COMMANDS_NAV_DESTINATION:
                body = sendOdd(navInfoModel.poiItemInfo);
                requestEntity = service.commandsODD(requestEntity, remoteCommandType, ApplicationUtil.getInstance().getVin(),body);
                break;
            default:
                break;
        }
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "navCommand", requestEntity, NavInfoModel.class);
        try {
            String response = NetConnectUtil.getResponse(getDatas(requestEntity));
            JSONObject error = GsonHelper.getJsonObject(response, "error");
            JSONObject commandResponse = GsonHelper.getJsonObject(response, "commandResponse");
            if (error != null) {
                try {
                    String code = error.getString("code");
                    String description = error.getString("description");
                    ErrorInfo errorInfo = new ErrorInfo();
                    errorInfo.setCode(code);
                    errorInfo.setMsg(description);
                    BusinessUtil.updateToFailPollingStatusBeforePolling(remoteCommandType, ApplicationUtil.getInstance().getVin(),manager);
                    throw new OnStarException(errorInfo.getCode(), errorInfo.getMsg());
                } catch (JSONException e) {
                    processError(remoteCommandType, e);
                }
            } else if (commandResponse != null) {
                try {
//                    if (RequestStatus.InProgress.getStringValue().equals(commandResponse.getString("status"))) {
                    String url = commandResponse.getString("url");
                    requestId = url.substring(url.lastIndexOf("s") + 2, url.length());
//                        if (remoteCommandType == RemoteCommandsType.COMMANDS_NAV_DESTINATION || remoteCommandType == RemoteCommandsType.COMMANDS_TBT_ROUTE) {
//                            saveHistoryToSql(requestId, navInfoModel.poiItemInfo, null, true);
//                            //将下发历史保存到历史记录中
//                            saveSearchHistory(navInfoModel.poiItemInfo);
//                        }
                    startPollVehicleStatus(remoteCommandType, requestId);
//                    }
                } catch (JSONException e) {
                    processError(remoteCommandType, e);
                }
            }
            return requestId;
        } catch (OnStarException on) {
            BusinessUtil.updateToFailPollingStatusBeforePolling(remoteCommandType, ApplicationUtil.getInstance().getVin(),manager);
            throw on;
        }
    }

    public void startPollVehicleStatus(RemoteCommandsType commandsType, String requestId) {
        PollingEntity entity = new PollingEntity();
        entity.setVin(ApplicationUtil.getInstance().getCurrentVehicle().getVin());
        entity.setToken(ApplicationUtil.getInstance().getToken());
        entity.setRequestType(commandsType.value());
        entity.setRequestId(requestId);
        manager.startPoll(entity);
    }

    private void processError(final RemoteCommandsType commandType, Exception e) throws OnStarException {
        ErrorInfo errorInfo = BusinessUtil.getErrorInfoByException(context, e);
        BusinessUtil.updateToFailPollingStatusBeforePolling(commandType, ApplicationUtil.getInstance().getVin(),manager);
        throw new OnStarException(errorInfo.getCode(), errorInfo.getMsg());
    }


    private String tbt(PoiItemInfo poiItemInfo) {
        VehicleCommand vecicleCommand = new VehicleCommand();
        VehicleTBT tbt = new VehicleTBT();

        DestinationLocation destinationLocation = new DestinationLocation();
        destinationLocation.setLat(String.valueOf(poiItemInfo.getLatitude()));
        destinationLocation.setLon(String.valueOf(poiItemInfo.getLongitude()));
//		tbt.setDestinationLocation(destinationLocation);
//
//		AdditionalDestinationInfo additionalDestinationInfo = new AdditionalDestinationInfo();
//		DestinationAddress destinationAddress = new DestinationAddress();
//		destinationAddress.setCity("shanghai");
//		destinationAddress.setCity("上海");
//		destinationAddress.setCountry("China");
//		destinationAddress.setState("");
//		destinationAddress.setStreet("xinyedalou");
//		destinationAddress.setStreet("新业大楼");
//		destinationAddress.setStreetNo("");
//		destinationAddress.setZipCode("200996");
//		additionalDestinationInfo.setDestinationAddress(destinationAddress);
//		additionalDestinationInfo.setDestinationType("ST_ADDR");
        tbt.setDestinationLocation(destinationLocation);

        vecicleCommand.setTbtDestination(tbt);
        return GsonHelper.toJson(vecicleCommand);
    }

    private String sendOdd(PoiItemInfo poiItemInfo) {
        VehicleCommand vecicleCommand = new VehicleCommand();
        VehicleNAV tbt = new VehicleNAV();

        DestinationLocation destinationLocation = new DestinationLocation();
        destinationLocation.setLat(String.valueOf(poiItemInfo.getLatitude()));
        destinationLocation.setLon(String.valueOf(poiItemInfo.getLongitude()));
        tbt.setDestinationLocation(destinationLocation);
        //
        AdditionalDestinationInfo additionalDestinationInfo = new AdditionalDestinationInfo();
        DestinationAddress destinationAddress = new DestinationAddress();

        //detail address
//        destinationAddress.setCity("shanghai");
//        destinationAddress.setCountry("China");
//        destinationAddress.setStreet("xinyedalou");
//        destinationAddress.setStreetNo("");
//        destinationAddress.setZipCode("200996");
//        additionalDestinationInfo.setDestinationType("ST_ADDR");

        // R5.5.5需要改成以下代码
        //gb18030
//        try{
//            destinationAddress.setState(new String("中国".getBytes(), "GB18030"));
//        }catch(UnsupportedEncodingException e) {
//
//        }
        destinationAddress.setState("China");
//        destinationAddress.setStreet(poiItemInfo.getSnippet());
//        destinationAddress.setCity(poiItemInfo.getCityName());
//        additionalDestinationInfo.setName(poiItemInfo.getTitle());
        additionalDestinationInfo.setDestinationAddress(destinationAddress);

//        LoadCityList cityList = new LoadCityList(context);
//        destinationAddress.setState(cityList.findByZhCity(poiItemInfo.getCityCode()));
////        destinationAddress.setState(poiItemInfo.getCityCode());
//        additionalDestinationInfo.setDestinationAddress(destinationAddress);
        tbt.setAdditionalDestinationInfo(additionalDestinationInfo);

        vecicleCommand.setNavDestination(tbt);
        log.d("sendOdd json body--->>>" + GsonHelper.toJson(vecicleCommand));
        return GsonHelper.toJson(vecicleCommand);
    }


    public Observable<List<FavoriteEntity>> doGetFavList() {
        return Observable.defer(new Func0<Observable<List<FavoriteEntity>>>() {
            @Override
            public Observable<List<FavoriteEntity>> call() {
                try {
                    return Observable.just(getFavoriteDestinationList());
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public List<FavoriteEntity> getFavoriteDestinationList() throws OnStarException {
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity = service.getFavoriteDestinationList(requestEntity, ApplicationUtil.getInstance().getIdpID());
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getFavoriteDestinationList", requestEntity);
        String response = NetConnectUtil.getResponse(getDatas(requestEntity));
        if (!CommonUtil.isNull(response)) {
            List<FavoriteEntity> favoriteDataLists = new Gson().fromJson(response,new TypeToken<ArrayList<FavoriteEntity>>(){}.getType());
            return favoriteDataLists;
        }
        return null;
    }

    public Observable<String> doDeleteFavoriteDestination(final PoiItemInfo deletePoiItemInfo) {
        return Observable.defer(new Func0<Observable<String>>() {
            @Override
            public Observable<String> call() {
                try {
                    return Observable.just(deleteFavoriteDestination(deletePoiItemInfo));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.DELETE)
    public String deleteFavoriteDestination(final PoiItemInfo deletePoiItemInfo) throws OnStarException {
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity = service.deleteFavoriteDestination(requestEntity, ApplicationUtil.getInstance().getIdpID(),
                String.valueOf(deletePoiItemInfo.getId()));
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "deleteFavoriteDestination", requestEntity, PoiItemInfo.class);
        return NetConnectUtil.getResponse(getDatas(requestEntity));
    }


    public Observable<String> doAddFavoriteDestination(final String name, final PoiItemInfo poiItemInfo) {
        return Observable.defer(new Func0<Observable<String>>() {
            @Override
            public Observable<String> call() {
                try {
                    return Observable.just(addFavoriteDestination(name, poiItemInfo));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public String addFavoriteDestination(String name, final PoiItemInfo poiItemInfo) throws OnStarException {
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity = service.addFavoriteDestination(requestEntity, ApplicationUtil.getInstance().getIdpID());
        requestEntity.setBody(GsonHelper.toJson(poiItemInfoToFavoriteEntity(poiItemInfo, name)));
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "addFavoriteDestination", requestEntity, String.class, PoiItemInfo.class);
        return NetConnectUtil.getResponse(getDatas(requestEntity));
    }

    private FavoriteEntity poiItemInfoToFavoriteEntity(PoiItemInfo info, String name) {
        FavoriteEntity entity = new FavoriteEntity();
        Coordinate coordinate = new Coordinate();
        DeviceUtil device = new DeviceUtil(context);
        coordinate.setLatitude(info.getLatitude());
        coordinate.setLongitude(info.getLongitude());
        entity.setPoiCoordinate(coordinate);
        entity.setPoiCityCode(info.getCityName());
        entity.setDeviceID(device.getDeviceID());
        entity.setPoiPhoneNumber(info.getTelphone());
        entity.setPoiAddress(info.getAddress());
        entity.setIdpID(ApplicationUtil.getInstance().getIdpID());
        entity.setPoiNickname(TextUtils.isEmpty(info.getNickName()) ? name : info.getNickName());
        entity.setPoiCatetory(info.getTypeDes() == null ? " " : info.getTypeDes());
        entity.setProvience("");
        entity.setPoiName(name);
        return entity;
    }

    private FavoriteEntity poiItemInfoToHomeOrCompany(PoiItemInfo info, MapChoosePoiType mapChoosePoiType) {
        FavoriteEntity entity = new FavoriteEntity();
        Coordinate coordinate = new Coordinate();
        DeviceUtil device = new DeviceUtil(context);
        coordinate.setLatitude(info.getLatitude());
        coordinate.setLongitude(info.getLongitude());
        entity.setPoiCoordinate(coordinate);
        entity.setPoiCityCode(info.getCityName());
        entity.setDeviceID(device.getDeviceID());
        entity.setPoiPhoneNumber(info.getTelphone());
        entity.setPoiAddress(info.getAddress());
        entity.setIdpID(ApplicationUtil.getInstance().getIdpID());
        if (!CommonUtil.isNull(info.getTitle())) {
            entity.setPoiNickname(info.getTitle());
        } else {
            entity.setPoiNickname("---");
        }
        entity.setPoiCatetory(info.getTypeDes() == null ? " " : info.getTypeDes());
        entity.setProvience("");
        entity.setPoiName(info.getTitle());
        if (mapChoosePoiType == MapChoosePoiType.HOME) {
            entity.setCustomCatetory("1");
        } else if (mapChoosePoiType == MapChoosePoiType.COMPANY) {
            entity.setCustomCatetory("2");
        }
        return entity;
    }


    public Observable<String> dosaveHomeOrCompanyAddressInfo(final PoiItemInfo poiItemInfo, final MapChoosePoiType mapChoosePoiType) {
        return Observable.defer(new Func0<Observable<String>>() {
            @Override
            public Observable<String> call() {
                try {
                    return Observable.just(saveHomeOrCompanyAddressInfo(poiItemInfo, mapChoosePoiType));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public String saveHomeOrCompanyAddressInfo(final PoiItemInfo poiItemInfo, MapChoosePoiType mapChoosePoiType) throws OnStarException {
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity = service.addFavoriteDestination(requestEntity, ApplicationUtil.getInstance().getIdpID());
        requestEntity.setBody(GsonHelper.toJson(poiItemInfoToHomeOrCompany(poiItemInfo, mapChoosePoiType)));
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "saveHomeOrCompanyAddressInfo", requestEntity, PoiItemInfo.class, MapChoosePoiType.class);
        try {
            return NetConnectUtil.getResponse(getDatas(requestEntity));
        } catch (HttpException e) {
            if (!CommonUtil.isNull(e.getErrorCode())
                    && e.getErrorCode().equalsIgnoreCase(ErrorEnum.SOMP_702.getStringValue())) {
                ErrorInfo errorInfo = new ErrorInfo();
                errorInfo.setCode(ErrorEnum.SOMP_702.getStringValue());
                throw new OnStarException(ErrorEnum.SOMP_702.getStringValue(), context.getString(R.string.nav_saveaddressinfo_fail));
            } else {
//                ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(context, e);
                throw new OnStarException("", context.getString(R.string.nav_saveaddressinfo_fail));
            }
        }
    }

    public Observable<NavAroundDealerResponseEntity> getAroundDealerList(final AroundDealerRequestEntity dealerRequestEntity) {
        return Observable.defer(new Func0<Observable<NavAroundDealerResponseEntity>>() {
            @Override
            public Observable<NavAroundDealerResponseEntity> call() {
                try {
                    return Observable.just((NavAroundDealerResponseEntity) GsonHelper.fromJson( getAroundDealerData(dealerRequestEntity),NavAroundDealerResponseEntity.class));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    /**
     * @Title: loadAroundDealer
     * @Description: 加载周边经销商数据
     */
    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public String getAroundDealerData(AroundDealerRequestEntity dealerRequestEntity) throws OnStarException {
        DealersService vehicleService = new DealersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        final ReqAroundDealersEntity aroundDealers = new ReqAroundDealersEntity();
        //aroundDealers.setCityCode("SH");			 		 //城市代码
        aroundDealers.setQueryType("ALL");                 //服务类型	 ALL / PRE_SALE / AFTER_SALE
        String vin = "";
        if (ApplicationUtil.getInstance().getCurrentVehicle()!=null) {
            aroundDealers.setDealerBrand(DealerBrandType.getDealerBrandTypeByDesc(ApplicationUtil.getInstance().getCurrentVehicle().getModelDesc())
                    .value());                                 //经销商品牌     ALL / BUICK / CHEVROLET / CADILLAC
            aroundDealers.setReturnPreferredDealer("true");  //是否返回首选经销商
            vin = ApplicationUtil.getInstance().getCurrentVehicle().getVin();
        } else {
            aroundDealers.setVin(vin);
            aroundDealers.setDealerBrand("ALL");             //经销商品牌     ALL / BUICK / CHEVROLET / CADILLAC
            aroundDealers.setReturnPreferredDealer("false"); //是否返回首选经销商
        }
        CoordinateEntity currentLocation = new CoordinateEntity();
        currentLocation.setLongitude(dealerRequestEntity.getLongitude());
        currentLocation.setLatitude(dealerRequestEntity.getLatitude());
        aroundDealers.setCurrentLocation(currentLocation);
        String subscriberID = ApplicationUtil.getInstance().getSubscriberID();
        String accountID = ApplicationUtil.getInstance().getAccountId();
        String vin2 = null;
        if (!CommonUtil.isNull(ApplicationUtil.getInstance().getVin())) {
            vin2 = ApplicationUtil.getInstance().getCurrentVehicle().getVin();
        }
//		String subscriberID = "00000000000108040604_00000001427682832649_00013";
//		String accountID = "1201761200";
//		String vin = "LSGAR5AL2G4240004";
//        LinkedHashMap<String, Object> coHashMap = new LinkedHashMap<String, Object>();
//        coHashMap.put(FinalConstants.HTTP_AUTHORIZATION, ApplicationUtil.getInstance().getToken());
//        requestEntity.setCustomHeads(coHashMap);

        if (CommonUtil.isNull(subscriberID)) {
            subscriberID = "1";
        }
        if (CommonUtil.isNull(accountID)) {
            accountID = "1";
        }
        if (CommonUtil.isNull(vin2)) {
            vin2 = "1";
        }

        requestEntity = vehicleService.getAroundDealersService(
                requestEntity,
                subscriberID,
                accountID,
                vin2,
                aroundDealers,
                dealerRequestEntity.getPageIndex(),
                dealerRequestEntity.getPageSize());
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getAroundDealerData", requestEntity, AroundDealerRequestEntity.class);
        return NetConnectUtil.getResponse(getDatas(requestEntity));
//        return AROUND_DEALER_JSON;
    }

    public Observable<List<MyFootprintStatisticDTO>> doGetFootPrintSummary() {
        return Observable.defer(new Func0<Observable<List<MyFootprintStatisticDTO>>>() {
            @Override
            public Observable<List<MyFootprintStatisticDTO>> call() {
                try {
                    return Observable.just(getFootPrintSummary());
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }


    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public List<MyFootprintStatisticDTO> getFootPrintSummary() throws OnStarException {
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity = service.getFootPrintSummary(requestEntity, ApplicationUtil.getInstance().getIdpID(), ApplicationUtil.getInstance().getAccountId(), ApplicationUtil.getInstance().getVin());
//        requestEntity = service.getFootPrintSummary(requestEntity, ApplicationUtil.getInstance().getIdpID(), ApplicationUtil.getInstance().getAccountId(), "LSGKR5WL0G0011C33");
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getFootPrintSummary", requestEntity);
        LogManager.getInstance().d("getFootPrintSummary url ------------->>" + requestEntity.getUrl());
        String response = NetConnectUtil.getResponse(getDatas(requestEntity));
        LogManager.getInstance().d("getFootPrintSummary response ------------->>" + response);
//        String response = SUMMARY_JSON;
        if (!CommonUtil.isNull(response)) {
            return new Gson().fromJson(response,new TypeToken<ArrayList<MyFootprintStatisticDTO>>(){}.getType());
        }
        return null;
    }

    /**
     * 概览模式 分享接口
     * @param longitude
     * @param latitude
     * @return
     * @throws OnStarException
     */
    public Observable<String> doGetOverViewFootPrintShareUrl(final String longitude, final String latitude) {
        return Observable.defer(new Func0<Observable<String>>() {
            @Override
            public Observable<String> call() {
                try {
                    return Observable.just(getOverViewFootPrintShareUrl(longitude,latitude));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public String getOverViewFootPrintShareUrl(String longitude,String latitude) throws OnStarException {
        FootPrintService service = new FootPrintService(Constants.CURRENT_PREFIX_H5_URL + Constants.SHARE_FOOTPRINT);//http://idt1.onstar.com.cn/mweb/mweb-main-rest/
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity = service.getShareUrlOfOverView(requestEntity,
                ApplicationUtil.getInstance().getIdpID(),
                ApplicationUtil.getInstance().getAccountId(),
                ApplicationUtil.getInstance().getVin(),
                longitude,
                latitude);
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getOverViewFootPrintShareUrl", requestEntity,String.class,String.class);
        LogManager.getInstance().d("getOverViewFootPrintShareUrl url ------------->>" + requestEntity.getUrl());
        String response = NetConnectUtil.getResponse(getDatas(requestEntity));
        LogManager.getInstance().d("getOverViewFootPrintShareUrl response ------------->>" + response);
//        String response = SUMMARY_JSON;
        return response;
    }

    /**
     * 详情模式 分享接口
     * @param longitude
     * @param latitude
     * @return
     */
    public Observable<String> doGetDetailFootPrintShareUrl(final String longitude, final String latitude,final String city,final String scale) {
        return Observable.defer(new Func0<Observable<String>>() {
            @Override
            public Observable<String> call() {
                try {
                    return Observable.just(getDetailFootPrintShareUrl(longitude,latitude,city,scale));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }


    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public String getDetailFootPrintShareUrl(String longitude,String latitude,String city,String scale) throws OnStarException {
        //EncryptUtil.decryptBase64(context, Constants.PREFIX_MWEB_URL) + Constants.SHARE_FOOTPRINT
        FootPrintService service = new FootPrintService(Constants.CURRENT_PREFIX_H5_URL + Constants.SHARE_FOOTPRINT);//http://idt1.onstar.com.cn/mweb/mweb-main-rest/
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity = service.getShareUrlOfDetail(requestEntity,
                ApplicationUtil.getInstance().getIdpID(),
                ApplicationUtil.getInstance().getAccountId(),
                ApplicationUtil.getInstance().getVin(),
                longitude,
                latitude,
                city,
                scale);
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getDetailFootPrintShareUrl", requestEntity,String.class,String.class,String.class,String.class);
        LogManager.getInstance().d("getDetailFootPrintShareUrl url ------------->>" + requestEntity.getUrl());
        String response = NetConnectUtil.getResponse(getDatas(requestEntity));
        LogManager.getInstance().d("getDetailFootPrintShareUrl response ------------->>" + response);
//        String response = SUMMARY_JSON;
        return response;
    }


    public Observable<List<MyFootprintDTO>> doGetFootPrintByCity(final String city) {
        return Observable.defer(new Func0<Observable<List<MyFootprintDTO>>>() {
            @Override
            public Observable<List<MyFootprintDTO>> call() {
                try {
                    return Observable.just(getFootPrintByCity(city));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public List<MyFootprintDTO> getFootPrintByCity(String city) throws OnStarException {
        /**
         * 防止乱码
         */
//        city = java.net.URLEncoder.encode(city);
        try {
            city = URLEncoder.encode(city, "UTF-8");
        } catch (Exception e) {
        }
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity = service.getFootPrintByCity(requestEntity, ApplicationUtil.getInstance().getIdpID(), ApplicationUtil.getInstance().getAccountId(), ApplicationUtil.getInstance().getVin(),city);
//        requestEntity = service.getFootPrintByCity(requestEntity, ApplicationUtil.getInstance().getIdpID(), ApplicationUtil.getInstance().getAccountId(), "LSGKR5WL0G0011C33", city);
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getFootPrintByCity", requestEntity, String.class);
        LogManager.getInstance().d("getFootPrintByCity url ------------->>" + requestEntity.getUrl());
        String response = NetConnectUtil.getResponse(getDatas(requestEntity));
        LogManager.getInstance().d("getFootPrintByCity response ------------->>" + response);
//        String response = "";
//        if (city.equals("上海")) {
//            response = CITY_JSON_SH;
//        } else {
//            response = CITY_JSON_BJ;
//        }
        if (!CommonUtil.isNull(response)) {
            List<MyFootprintDTO> list = new Gson().fromJson( response,new TypeToken<ArrayList<MyFootprintDTO>>(){}.getType());
            LogManager.getInstance().d("getFootPrintByCity url ------------->>" + list);
            return list;
        }
        return null;
    }

    public Observable<String> doDeleteCityPoi(final String seqId) {
        return Observable.defer(new Func0<Observable<String>>() {
            @Override
            public Observable<String> call() {
                try {
                    return Observable.just(deleteFootPrintById(seqId));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }


    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public String deleteFootPrintById(String id) throws OnStarException {
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity = service.deleteFootPrint(requestEntity, ApplicationUtil.getInstance().getIdpID(), ApplicationUtil.getInstance().getAccountId(), ApplicationUtil.getInstance().getVin(),id);
//        requestEntity = service.deleteFootPrint(requestEntity, ApplicationUtil.getInstance().getIdpID(), ApplicationUtil.getInstance().getAccountId(), "LSGKR5WL0G0011C33", id);
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "deleteFootPrintById", requestEntity, String.class);
        LogManager.getInstance().d("deleteFootPrintById url ------------->>" + requestEntity.getUrl());
        String response = NetConnectUtil.getResponse(getDatas(requestEntity));
        LogManager.getInstance().d("deleteFootPrintById response ------------->>" + response);
//        String response="";
//        if(city.equals("上海")){
//            response = CITY_JSON_SH;
//        }else {
//            response = CITY_JSON_BJ;
//        }
        if (!CommonUtil.isNull(response)) {
            ResCode resCode = GsonHelper.fromJson( response,ResCode.class);
            if (resCode != null) {
                return resCode.getCode();
            }
        }
        return null;
    }

    private final static String SUMMARY_JSON = "[\n" +
            "  {\n" +
            "    \"vin\": \"LSGKYTF66G4DR76HY\",\n" +
            "    \"destCity\": \"上海\",\n" +
            "    \"lastDestLatitude\": 31.301549,\n" +
            "    \"lastDestLongitude\": 121.436938,\n" +
            "    \"destStreetName\": \"南京东路\",\n" +
            "    \"destStreetNum\": \"1\",\n" +
            "    \"stateCount\": 100,\n" +
            "    \"cityCount\": 200,\n" +
            "    \"totalCount\": 500,\n" +
            "    \"totalRank\": 20\n" +
            "  },\n" +
            "  {\n" +
            "    \"vin\": \"LSGKYTF66G4DR76HY\",\n" +
            "    \"destCity\": \"北京\",\n" +
            "    \"lastDestLatitude\": 40.127952,\n" +
            "    \"lastDestLongitude\": 116.32204,\n" +
            "    \"destStreetName\": \"南京东路\",\n" +
            "    \"destStreetNum\": \"1\",\n" +
            "    \"stateCount\": 100,\n" +
            "    \"cityCount\": 200,\n" +
            "    \"totalCount\": 500,\n" +
            "    \"totalRank\": 20\n" +
            "  }\n" +
            "]";

    private final static String CITY_JSON_BJ = "[\n" +
            "  {\n" +
            "    \"vin\": \"333\",\n" +
            "    \"destLongitude\":116.32204,\n" +
            "    \"destLatitude\": 40.127952,\n" +
            "    \"destCountry\": \"中国\",\n" +
            "    \"destState\": \"上海\",\n" +
            "    \"destCity\": \"北京\",\n" +
            "    \"destStreetName\": \"南京东路\",\n" +
            "    \"destStreetNum\": \"1号\",\n" +
            "    \"lastFlag\": 1,\n" +
            "    \"processingStartTime\": \"2016-07-25\",\n" +
            "    \"statusCode\": 104\n" +
            "  },\n" +
            "  {\n" +
            "    \"vin\": \"333\",\n" +
            "    \"destLongitude\": 117.155627,\n" +
            "    \"destLatitude\": 39.923941,\n" +
            "    \"destCountry\": \"中国\",\n" +
            "    \"destState\": \"上海\",\n" +
            "    \"destCity\": \"北京\",\n" +
            "    \"destStreetName\": \"南京东路\",\n" +
            "    \"destStreetNum\": \"1号\",\n" +
            "    \"lastFlag\": 1,\n" +
            "    \"processingStartTime\": \"2016-07-25\",\n" +
            "    \"statusCode\": 104\n" +
            "  },\n" +
            "    {\n" +
            "    \"vin\": \"333\",\n" +
            "    \"destLongitude\": 116.32616,\n" +
            "    \"destLatitude\": 39.715096,\n" +
            "    \"destCountry\": \"中国\",\n" +
            "    \"destState\": \"上海\",\n" +
            "    \"destCity\": \"北京\",\n" +
            "    \"destStreetName\": \"南京东路\",\n" +
            "    \"destStreetNum\": \"1号\",\n" +
            "    \"lastFlag\": 1,\n" +
            "    \"processingStartTime\": \"2016-07-25\",\n" +
            "    \"statusCode\": 104\n" +
            "  }\n" +
            "]\n";
    private final static String CITY_JSON_SH = "[\n" +
            "  {\n" +
            "    \"vin\": \"333\",\n" +
            "    \"destLongitude\":121.436938,\n" +
            "    \"destLatitude\": 31.301549,\n" +
            "    \"destCountry\": \"中国\",\n" +
            "    \"destState\": \"上海\",\n" +
            "    \"destCity\": \"上海\",\n" +
            "    \"destStreetName\": \"南京东路\",\n" +
            "    \"destStreetNum\": \"1号\",\n" +
            "    \"lastFlag\": 1,\n" +
            "    \"processingStartTime\": \"2016-07-25\",\n" +
            "    \"statusCode\": 104\n" +
            "  },\n" +
            "  {\n" +
            "    \"vin\": \"333\",\n" +
            "    \"destLongitude\": 121.181506,\n" +
            "    \"destLatitude\": 31.498474,\n" +
            "    \"destCountry\": \"中国\",\n" +
            "    \"destState\": \"上海\",\n" +
            "    \"destCity\": \"上海\",\n" +
            "    \"destStreetName\": \"南京东路\",\n" +
            "    \"destStreetNum\": \"1号\",\n" +
            "    \"lastFlag\": 1,\n" +
            "    \"processingStartTime\": \"2016-07-25\",\n" +
            "    \"statusCode\": 104\n" +
            "  },\n" +
            "    {\n" +
            "    \"vin\": \"333\",\n" +
            "    \"destLongitude\": 121.729449,\n" +
            "    \"destLatitude\": 31.051284,\n" +
            "    \"destCountry\": \"中国\",\n" +
            "    \"destState\": \"上海\",\n" +
            "    \"destCity\": \"上海\",\n" +
            "    \"destStreetName\": \"南京东路\",\n" +
            "    \"destStreetNum\": \"1号\",\n" +
            "    \"lastFlag\": 1,\n" +
            "    \"processingStartTime\": \"2016-07-25\",\n" +
            "    \"statusCode\": 104\n" +
            "  }\n" +
            "]";

    private static final String AROUND_DEALER_JSON = "{\n" +
            "    \"dealers\": [\n" +
            "        {\n" +
            "            \"isPreferredDealer\": true, \n" +
            "            \"id\": \"00000000000002317533_00000001297959787514_00073\", \n" +
            "            \"dealerName\": \"上海启海汽车销售有限公司\", \n" +
            "            \"distanceWithUnit\": \"52.5 km\", \n" +
            "            \"distance\": 52.5, \n" +
            "            \"cityCode\": \"310000\", \n" +
            "            \"partyID\": \"00000000000002317533_00000001297959787514_00073\", \n" +
            "            \"dealerCode\": \"2200638\", \n" +
            "            \"telephone\": \"02169630000\", \n" +
            "            \"address\": \"上海市崇明县城桥镇秀山路101号 \", \n" +
            "            \"locationCoordinate\": {\n" +
            "                \"longitude\": 121.385242, \n" +
            "                \"latitude\": 31.640042\n" +
            "            }\n" +
            "        }, \n" +
            "        {\n" +
            "            \"id\": \"00000000000000020229_00000001260263236390_00937\", \n" +
            "            \"dealerName\": \"上海太平洋申隆汽车销售服务有限公司\", \n" +
            "            \"distanceWithUnit\": \"2.3 km\", \n" +
            "            \"distance\": 2.3, \n" +
            "            \"cityCode\": \"310000\", \n" +
            "            \"partyID\": \"00000000000000020229_00000001260263236390_00937\", \n" +
            "            \"dealerCode\": \"CH1065\", \n" +
            "            \"telephone\": \"0341333337\", \n" +
            "            \"address\": \"上海市闵行区吴中路1389号 \", \n" +
            "            \"locationCoordinate\": {\n" +
            "                \"longitude\": 121.373916, \n" +
            "                \"latitude\": 31.172471\n" +
            "            }\n" +
            "        }, \n" +
            "        {\n" +
            "            \"id\": \"00000000000000010935_00000001258621303465_09296\", \n" +
            "            \"dealerName\": \"上海太平洋申隆汽车销售服务有限公司\", \n" +
            "            \"distanceWithUnit\": \"2.3 km\", \n" +
            "            \"distance\": 2.3, \n" +
            "            \"cityCode\": \"310000\", \n" +
            "            \"partyID\": \"00000000000000010935_00000001258621303465_09296\", \n" +
            "            \"dealerCode\": \"2200128\", \n" +
            "            \"telephone\": \"02134133337\", \n" +
            "            \"address\": \"上海市闵行区吴中路1389号 \", \n" +
            "            \"locationCoordinate\": {\n" +
            "                \"longitude\": 121.373916, \n" +
            "                \"latitude\": 31.172471\n" +
            "            }\n" +
            "        }, \n" +
            "        {\n" +
            "            \"id\": \"00000000000000010935_00000001258621296398_08438\", \n" +
            "            \"dealerName\": \"上海永达通豪汽车销售服务有限公司\", \n" +
            "            \"distanceWithUnit\": \"5.2 km\", \n" +
            "            \"distance\": 5.2, \n" +
            "            \"cityCode\": \"310000\", \n" +
            "            \"partyID\": \"00000000000000010935_00000001258621296398_08438\", \n" +
            "            \"dealerCode\": \"2200136\", \n" +
            "            \"telephone\": \"02164656789\", \n" +
            "            \"address\": \"上海市闵行区吴宝路799号 \", \n" +
            "            \"locationCoordinate\": {\n" +
            "                \"longitude\": 121.342307, \n" +
            "                \"latitude\": 31.169431\n" +
            "            }\n" +
            "        }, \n" +
            "        {\n" +
            "            \"id\": \"00000000000000020225_00000001260263229907_00816\", \n" +
            "            \"dealerName\": \"上海永达通豪汽车销售服务有限公司\", \n" +
            "            \"distanceWithUnit\": \"5.2 km\", \n" +
            "            \"distance\": 5.2, \n" +
            "            \"cityCode\": \"310000\", \n" +
            "            \"partyID\": \"00000000000000020225_00000001260263229907_00816\", \n" +
            "            \"dealerCode\": \"CH1010\", \n" +
            "            \"telephone\": \"064656789\", \n" +
            "            \"address\": \"上海市闵行区吴宝路799号 \", \n" +
            "            \"locationCoordinate\": {\n" +
            "                \"longitude\": 121.342307, \n" +
            "                \"latitude\": 31.169431\n" +
            "            }\n" +
            "        }, \n" +
            "        {\n" +
            "            \"id\": \"a7f9ed76-2964-4bc3-b408-a630e55a03f9\", \n" +
            "            \"dealerName\": \"上海汽车工业销售有限公司\", \n" +
            "            \"distanceWithUnit\": \"5.7 km\", \n" +
            "            \"distance\": 5.7, \n" +
            "            \"cityCode\": \"310000\", \n" +
            "            \"partyID\": \"a7f9ed76-2964-4bc3-b408-a630e55a03f9\", \n" +
            "            \"dealerCode\": \"CH1017\", \n" +
            "            \"telephone\": \"02124011188\", \n" +
            "            \"address\": \"上海市徐汇区武康路390号 \", \n" +
            "            \"locationCoordinate\": {\n" +
            "                \"longitude\": 121.438579, \n" +
            "                \"latitude\": 31.205729\n" +
            "            }\n" +
            "        }, \n" +
            "        {\n" +
            "            \"id\": \"00000000000000010935_00000001258621302154_09127\", \n" +
            "            \"dealerName\": \"上海绿地徐通汽车销售服务有限公司\", \n" +
            "            \"distanceWithUnit\": \"6.3 km\", \n" +
            "            \"distance\": 6.3, \n" +
            "            \"cityCode\": \"310000\", \n" +
            "            \"partyID\": \"00000000000000010935_00000001258621302154_09127\", \n" +
            "            \"dealerCode\": \"2200259\", \n" +
            "            \"telephone\": \"054960760\", \n" +
            "            \"address\": \"船厂路185号 \", \n" +
            "            \"locationCoordinate\": {\n" +
            "                \"longitude\": 121.460498, \n" +
            "                \"latitude\": 31.185394\n" +
            "            }\n" +
            "        }, \n" +
            "        {\n" +
            "            \"id\": \"00000000000000020229_00000001260263207341_00025\", \n" +
            "            \"dealerName\": \"上海绿地徐通汽车销售服务有限公司\", \n" +
            "            \"distanceWithUnit\": \"6.3 km\", \n" +
            "            \"distance\": 6.3, \n" +
            "            \"cityCode\": \"310000\", \n" +
            "            \"partyID\": \"00000000000000020229_00000001260263207341_00025\", \n" +
            "            \"dealerCode\": \"CH1045\", \n" +
            "            \"telephone\": \"064165666\", \n" +
            "            \"address\": \"船厂路185号 \", \n" +
            "            \"locationCoordinate\": {\n" +
            "                \"longitude\": 121.460498, \n" +
            "                \"latitude\": 31.185394\n" +
            "            }\n" +
            "        }, \n" +
            "        {\n" +
            "            \"id\": \"00000000000000031587_00000001262808189659_00091\", \n" +
            "            \"dealerName\": \"上海众国同普汽车有限公司\", \n" +
            "            \"distanceWithUnit\": \"7.6 km\", \n" +
            "            \"distance\": 7.6, \n" +
            "            \"cityCode\": \"310000\", \n" +
            "            \"partyID\": \"00000000000000031587_00000001262808189659_00091\", \n" +
            "            \"dealerCode\": \"2200428\", \n" +
            "            \"telephone\": \"02157207722\", \n" +
            "            \"address\": \"上海市普陀区同普路1236号 \", \n" +
            "            \"locationCoordinate\": {\n" +
            "                \"longitude\": 121.371281, \n" +
            "                \"latitude\": 31.232769\n" +
            "            }\n" +
            "        }, \n" +
            "        {\n" +
            "            \"id\": \"00000000000000010935_00000001258621312236_10265\", \n" +
            "            \"dealerName\": \"上海众国同普汽车有限公司\", \n" +
            "            \"distanceWithUnit\": \"7.6 km\", \n" +
            "            \"distance\": 7.6, \n" +
            "            \"cityCode\": \"310000\", \n" +
            "            \"partyID\": \"00000000000000010935_00000001258621312236_10265\", \n" +
            "            \"dealerCode\": \"CH1096\", \n" +
            "            \"telephone\": \"052708650\", \n" +
            "            \"address\": \"上海市普陀区同普路1236号 \", \n" +
            "            \"locationCoordinate\": {\n" +
            "                \"longitude\": 121.371281, \n" +
            "                \"latitude\": 31.232769\n" +
            "            }\n" +
            "        }, \n" +
            "        {\n" +
            "            \"id\": \"00000000000000010935_00000001258621222367_00394\", \n" +
            "            \"dealerName\": \"上海安吉名门汽车服务有限公司\", \n" +
            "            \"distanceWithUnit\": \"9.2 km\", \n" +
            "            \"distance\": 9.2, \n" +
            "            \"cityCode\": \"310000\", \n" +
            "            \"partyID\": \"00000000000000010935_00000001258621222367_00394\", \n" +
            "            \"dealerCode\": \"2200187\", \n" +
            "            \"telephone\": \"02152839299\", \n" +
            "            \"address\": \"上海市铜川路1366号101-105室 \", \n" +
            "            \"locationCoordinate\": {\n" +
            "                \"longitude\": 121.394725, \n" +
            "                \"latitude\": 31.251159\n" +
            "            }\n" +
            "        }\n" +
            "    ], \n" +
            "    \"pageable\": {\n" +
            "        \"pageNumber\": 0, \n" +
            "        \"pageSize\": 10, \n" +
            "        \"offset\": 0, \n" +
            "        \"totalSize\": 56\n" +
            "    }\n" +
            "}";
}
